package com.jintian.smart.kernel.flowable.component;

import com.jintian.smart.kernel.core.flow.ActionType;
import com.jintian.smart.kernel.core.flow.FlowAction;
import com.jintian.smart.kernel.core.flow.IFlowAction;
import com.jintian.smart.kernel.core.flow.IFlowOperation;
import com.jintian.smart.kernel.flowable.domain.view.FlowBizVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@DubboService(timeout = 5000)
public class DefaultFlowOperation implements IFlowOperation<FlowBizVo>, BeanPostProcessor {
    private static final Map<FlowAction, IFlowAction<?>> actionMap = new HashMap<>();

    @Override
    public void registerProcessAction(FlowAction action, IFlowAction<?> taskAction) {
        if (action.isActionType(ActionType.flow)) {
            actionMap.put(action, taskAction);
        }
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof IFlowAction) {
            @SuppressWarnings("rawtypes")
            IFlowAction ta = (IFlowAction) bean;
            this.registerProcessAction(ta.getAction(), ta);
        }
        return bean;
    }

    @Override
    public FlowBizVo query(String bizId, String bizClass, String process) throws Exception {
        return (FlowBizVo) actionMap.get(FlowAction.query).execute(bizId, bizClass, process);
    }
}
